package in.iqing.view.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import butterknife.Bind;
import butterknife.OnClick;
import in.iqing.app.R;
import in.iqing.base.BaseActivity;
import in.iqing.control.api.ApiHelper;
import in.iqing.control.api.callback.RegisterCallback;
import in.iqing.control.api.callback.RequestCallback;
import in.iqing.control.helper.LogHelper;
import in.iqing.control.util.MiscUtil;
import in.iqing.control.util.ToastUtil;
import in.iqing.model.bean.AuthResult;
import in.iqing.model.bean.User;
import in.iqing.model.sp.AccountSP;

/**
 * Created by ZuoShu on 15/7/6.
 */
public class RegisterActivity extends BaseActivity {
    @Bind(R.id.mobile_edit)
    EditText mobile;

    @Bind(R.id.verify_edit)
    EditText verifyEdit;

    @Bind(R.id.send_verify_code_button)
    Button sendVerifyButton;

    @Bind(R.id.username_edit)
    EditText username;

    @Bind(R.id.password_edit)
    EditText password;

    @Bind(R.id.password_confirm_edit)
    EditText confirmPassword;

    private Handler uiHandler;

    private static final int START_TIMER = 1;
    private static final int COUNT_TIME = 2;
    private static final int END_TIMER = 3;

    private RequestVerifyCallback requestVerifyCallback;
    private RegisterCallback registerCallback;

    private ProgressDialog loadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
    }

    @Override
    protected void onInitialize(Bundle savedInstanceState) {
        super.onInitialize(savedInstanceState);
        requestVerifyCallback = new RequestVerifyCallback();
        registerCallback = new ExtRegisterCallback();
        uiHandler = new UIHandler();
    }

    @OnClick(R.id.back)
    public void onBackClick(View v) {
        finish();
    }

    @OnClick(R.id.send_verify_code_button)
    public void onSendVerifyClick(View v) {
        String mobileString = mobile.getText().toString();
        if (TextUtils.isEmpty(mobileString)) {
            mobile.setError(getString(R.string.activity_register_empty_mobile));
            return;
        }

        if (!MiscUtil.isValidMobile(mobileString)) {
            mobile.setError(getString(R.string.activity_register_invalid_mobile));
            return;
        }
        requestVerify(mobileString);
    }

    private void requestVerify(String mobile) {
        ApiHelper.getSingleton().requestVerify(VOLLEY_TAG, mobile, requestVerifyCallback);
    }

    @OnClick(R.id.register_button)
    public void onRegisterClick(View v) {
        String mobileString = mobile.getText().toString();
        String verifyString = verifyEdit.getText().toString();
        String usernameString = username.getText().toString();
        String passwordString = password.getText().toString();
        String passwordConfirmString = confirmPassword.getText().toString();
        if (TextUtils.isEmpty(mobileString)) {
            mobile.setError(getString(R.string.activity_register_empty_mobile));
            mobile.requestFocus();
            return;
        }

        if (!MiscUtil.isValidMobile(mobileString)) {
            mobile.setError(getString(R.string.activity_register_invalid_mobile));
            mobile.requestFocus();
            return;
        }

        if (!MiscUtil.isValidVerifyCode(verifyString)) {
            verifyEdit.setError(getString(R.string.activity_register_invalid_verify_code));
            verifyEdit.requestFocus();
            return;
        }

        if (!MiscUtil.isValidUsername(usernameString)) {
            username.setError(getString(R.string.activity_register_invalid_username));
            username.requestFocus();
            return;
        }

        if (!MiscUtil.isValidPassword(passwordString)) {
            password.setError(getString(R.string.activity_register_invalid_password));
            password.requestFocus();
            return;
        }

        if (!passwordConfirmString.equals(passwordString)) {
            confirmPassword.setError(getString(R.string.activity_register_invalid_confirm_password));
            confirmPassword.requestFocus();
            return;
        }

        ApiHelper.getSingleton().register(VOLLEY_TAG, mobileString, verifyString, usernameString, passwordString, registerCallback);
    }


    @Override
    protected void onStop() {
        super.onStop();
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
    }

    private class UIHandler extends Handler {
        private int count = 60;
        private static final long ONE_SECOND = 1000l;

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case START_TIMER:
                    count = 60;
                    sendVerifyButton.setEnabled(false);
                    sendVerifyButton.setText(getString(R.string.activity_register_count, String.valueOf(count)));
                    sendEmptyMessageDelayed(COUNT_TIME, ONE_SECOND);
                    break;
                case COUNT_TIME:
                    count--;
                    if (count == 0) {
                        sendVerifyButton.setEnabled(true);
                        sendVerifyButton.setText(R.string.activity_register_send_verify_code);
                    } else {
                        sendVerifyButton.setText(getString(R.string.activity_register_count, String.valueOf(count)));
                        sendEmptyMessageDelayed(COUNT_TIME, ONE_SECOND);
                    }
                    break;
            }
        }
    }

    private class RequestVerifyCallback extends RequestCallback {

        @Override
        public void onSuccess() {
            uiHandler.sendEmptyMessage(START_TIMER);
            LogHelper.warn(TAG, "request verify success");
        }

        @Override
        public void onFailure(int code, String msg) {
            super.onFailure(code, msg);
            switch (code) {
                case AuthResult.MOBILE_DUPLICATE:
                    ToastUtil.show(getContext(), R.string.common_error_auth_9);
                    break;
                default:
                    ToastUtil.showError(getContext(), code, msg);
                    break;
            }
        }
    }

    private class ExtRegisterCallback extends RegisterCallback {

        @Override
        public void onFinish() {
            super.onFinish();
            if (loadingDialog != null) {
                loadingDialog.dismiss();
            }
        }

        @Override
        public void onStart() {
            super.onStart();
            loadingDialog = ProgressDialog.show(
                    getActivity(),
                    null,
                    getString(R.string.activity_register_registering),
                    true,
                    false
            );
        }

        @Override
        public void onFailure(int code, String msg) {
            super.onFailure(code, msg);
            switch (code) {
                case AuthResult.SERVER_FAILED:
                    ToastUtil.show(getContext(), R.string.common_error_auth_server_error);
                    break;
                case AuthResult.CODE_INVALID:
                    ToastUtil.show(getContext(), R.string.common_error_auth_6);
                    break;
                case AuthResult.MOBILE_DUPLICATE:
                    ToastUtil.show(getContext(), R.string.common_error_auth_9);
                    break;
                default:
                    ToastUtil.showError(getContext(), code, msg);
                    break;
            }
            if (loadingDialog != null) {
                loadingDialog.dismiss();
            }
        }

        @Override
        public void onSuccess(User user) {
            AccountSP.setMobile(user.getMobile());
            AccountSP.setUserName(user.getUsername());
            AccountSP.setUserId(user.getId());
            setResult(Activity.RESULT_OK);
            finish();
        }
    }


}
